package com.gonsin.gnews.service;

import com.gonsin.gnews.annotations.bean.ConfigValueBean;
import com.gonsin.gnews.annotations.model.ConfigValueModel;
import com.gonsin.gnews.annotations.services.IConfigValueService;
import com.gonsin.gnews.mapper.ConfigValueMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.gonsin.gnews.service.NewsTemplateServiceImpl.general;

@Service
public class NewsConfigValueServiceImpl implements IConfigValueService {

    @Autowired private ConfigValueMapper valueMapper;

    @Override
    public ConfigValueModel getConfigValue(String edificeKey, String platform) {
        ConfigValueBean bean = valueMapper.getConfig(edificeKey, platform);
        if(bean == null){
            return null;
        }
        ConfigValueModel value = new ConfigValueModel();
        value.setEdificeKey(edificeKey);
        value.setPlatform(platform);
        value.setItems(new ArrayList<>(bean.getContent()));
        return value;
    }

    @Override
    public ConfigValueModel updateConfigValue(ConfigValueModel model) {

        ConfigValueBean bean = valueMapper.getConfig(model.getEdificeKey(), model.getPlatform());
        if(bean == null){
            bean = new ConfigValueBean();
            bean.setEdificeKey(model.getEdificeKey());
            bean.setPlatform(model.getPlatform());
            bean.setConfigValueKey(general("configValue"));
            bean.setContent(model.getItems());
            valueMapper.insertConfig(bean);
            return model;
        }

        bean.setContent(model.getItems());
        valueMapper.updateConfig(bean);
        return model;
    }
}
